﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;


using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;
namespace WP.RM.Form
{
    public partial class frmRMOtherSalaryInputMtn : BaseMtn
    {
        private bool[] mDtlColumnReadOnlyArray;
        private bool m_bCanTrigerCellValueChangedEven =false ;
        private string mstrTableName = "rmWorkerOtherSalary";
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private bool m_bSettingStatus = false;
        private bool mPressExit = false;
        private bool mblnAbleToOtherSalary = false;
        private enum DtlCol
        {
            RowSeqNo = 0,Sel, WorkDate, WorkShopSeqNo, WorkShopName, WorkerRecID, WorkerID, WorkerName, 
            HourlySalary,HourlyCost, HoursOnCost,
            /// <summary>
            /// 绩效工资
            /// </summary>
            PRPSalary, 
            RewardAndPenalties, OverSpend, AddAndReduce, OverTimeSalary, Subsidy, 
            WithHoldAndRemitTax, Remark, Posted,
            RecID, ValueChanged, DelButton 
        }

        public frmRMOtherSalaryInputMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));           
            this.DesignTabsName = "tbpGeneral";            
            this.MinimumSize = this.Size;
            mblnAbleToOtherSalary = CvtFunc.ToBoolean(DataFunctions.GetFieldValue("muser", "AbleToOtherSalary", "userName='" + SysVar.UserName + "'"));
            btnPost.Visible = mblnAbleToOtherSalary;
            InitGridDtl();
        }

        
        #region Define Variable
        private bool mblnSettingStatus = false;
        #endregion

        #region ***Form Events

        private void frmRMOtherSalaryInputMtn_Load(object sender, EventArgs e)
        {
            //FillLookUpInfo();
            FillTree();
            InitGridDtl(); 
            FillDtl("");
        }
        private void frmRMOtherSalaryInputMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvInputDtl);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            
            if (this.dgvInputDtl.CurrentRow !=null )
            {
                if (!Update_Detail(this.dgvInputDtl.CurrentRow)) return;
            }
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            ToExcel.DataGirdViewToExcel(dgvInputDtl); 
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            //Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            //Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            //Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            //Nevigate(this.dgList, NavigateOrient.Bottom);
        }        
       
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }
       
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
           
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            RM.BusinessRule.RMWorkQtyInputHdrBRL mBRL = new WP.RM.BusinessRule.RMWorkQtyInputHdrBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }
        
        

        protected override void ShowOtherData()
        {
            base.ShowOtherData();
            
        }

        

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("WorkShopSeqNo", "rmWorkShop", "WorkShopSeqNo", "ubtWorkShopSeqNo");
            SetFieldLookUpInfo("WorkShopName", "rmWorkShop", "WorkShopName", "ubtWorkShopSeqNo");

            SetFieldLookUpInfo("WorkGroupSeqNo", "rmWorkGroup", "SeqNo", "ubtWorkGroupSeqNo");
            SetFieldLookUpInfo("WorkGroupName", "rmWorkGroup", "WorkGroupName", "ubtWorkGroupSeqNo");

            SetFieldLookUpInfo("WorkingProcedureID", "rmWorkingProcedure", "WorkingProcedureID", "ubtWorkingProcedureID");
            SetFieldLookUpInfo("WorkingProcedureName", "rmWorkingProcedure", "WorkingProcedureName", "ubtWorkingProcedureID");

            SetFieldLookUpInfo("ProductFItemID", "rmProduct", "ProductFItemID", "ubtProductFItemID");
            SetFieldLookUpInfo("ProductID", "rmProduct", "ProductID", "ubtProductFItemID");
            SetFieldLookUpInfo("ProductName", "rmProduct", "ProductName", "ubtProductFItemID");
            SetFieldLookUpInfo("Unit", "imUnit", "Unit", "ubtUnit");
        }

        #endregion Form Functions***

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " And WorkShopSeqNo like '" + strMaterialID + "'";
                FillDtl(strCond);
            }
        }

        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select WorkShopSeqNo,WorkShopName from rmWorkShop order by WorkShopSeqNo";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["WorkShopSeqNo"]) + "-" + CvtFunc.ToString(drType["WorkShopName"]));
                this.tvTree.Nodes.Add(tvNode);
            }
            dbcon.CloseCon();
        }

       



        #region Input Detail GRID

        private void InitGridDtl()
        {
            //RowSeqNo, WorkDate, WorkShopSeqNo, WorkShopName, WorkerRecID, WorkerID, WorkerName,            
            this.dgvInputDtl.Columns.Clear();
            this.dgvInputDtl.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colSel = new DataGridViewCheckBoxColumn();
            colSel.HeaderText = "选择";
            colSel.Visible = true;
            colSel.Name = "Sel";
            colSel.Width = 50;
            colSel.ReadOnly =false;
            colSel.SortMode = DataGridViewColumnSortMode.NotSortable;
            if (mblnAbleToOtherSalary)
            {
                colSel.Visible = true;
                btnSelAll.Visible = true;
                btnUnSelAll.Visible = true;
            }
            else
            {
                colSel.Visible = false;
                btnSelAll.Visible = false ;
                btnUnSelAll.Visible = false ;
            }

            CalendarColumn colWorkDate = new CalendarColumn();
            colWorkDate.HeaderText = "日期";
            colWorkDate.Width = 70;
            colWorkDate.Name = "WorkDate";
            colWorkDate.ReadOnly = false;
            colWorkDate.Visible = true;

            TextLookUpColumn colWorkShopSeqNo = new TextLookUpColumn();
            colWorkShopSeqNo.HeaderText = "车间编号";
            colWorkShopSeqNo.Width = 100;
            colWorkShopSeqNo.Name = "WorkShopSeqNo";
            colWorkShopSeqNo.ReadOnly = false;
            colWorkShopSeqNo.Visible = true;

            DataGridViewTextBoxColumn colWorkShopName = new DataGridViewTextBoxColumn();
            colWorkShopName.HeaderText = "车间名称";
            colWorkShopName.Width = 100;
            colWorkShopName.Name = "WorkShopName";
            colWorkShopName.ReadOnly = true;
            colWorkShopName.Visible = true;

            DataGridViewTextBoxColumn colWorkerRecID = new DataGridViewTextBoxColumn();
            colWorkerRecID.HeaderText = "员工代码";
            colWorkerRecID.Width = 100;
            colWorkerRecID.Name = "WorkerRecID";
            colWorkerRecID.ReadOnly = false;
            colWorkerRecID.Visible = false;

            TextLookUpColumn colWorkerID = new TextLookUpColumn();
            colWorkerID.HeaderText = "员工代码";
            colWorkerID.Width = 100;
            colWorkerID.Name = "WorkerID";
            colWorkerID.ReadOnly = false;
            colWorkerID.Visible = true;

            DataGridViewTextBoxColumn colWorkerName = new DataGridViewTextBoxColumn();
            colWorkerName.HeaderText = "员工姓名";
            colWorkerName.Width = 100;
            colWorkerName.Name = "WorkerName";
            colWorkerName.ReadOnly = false;
            colWorkerName.Visible = true;

            //HoursOnCost,HourlyCost,HourlySalary, RewardAndPenalties,
            DataGridViewTextBoxColumn colHoursOnCost = new DataGridViewTextBoxColumn();
            colHoursOnCost.HeaderText = "计时工时";
            colHoursOnCost.Width = 100;
            colHoursOnCost.Name = "HoursOnCost";
            colHoursOnCost.ReadOnly = false;
            colHoursOnCost.Visible = true;

            DataGridViewTextBoxColumn colHourlyCost = new DataGridViewTextBoxColumn();
            colHourlyCost.HeaderText = "计时工价";
            colHourlyCost.Width = 100;
            colHourlyCost.Name = "HourlyCost";
            colHourlyCost.ReadOnly = false;
            colHourlyCost.Visible = true;

            DataGridViewTextBoxColumn colHourlySalary = new DataGridViewTextBoxColumn();
            colHourlySalary.HeaderText = "计时工资";
            colHourlySalary.Width = 100;
            colHourlySalary.Name = "HourlySalary";
            colHourlySalary.ReadOnly = false;
            colHourlySalary.Visible = true;

            DataGridViewTextBoxColumn colPRPSalary = new DataGridViewTextBoxColumn();
            colHourlySalary.HeaderText = "绩效工资";
            colHourlySalary.Width = 100;
            colHourlySalary.Name = "PRPSalary";
            colHourlySalary.ReadOnly = false;
            colHourlySalary.Visible = true;

            DataGridViewTextBoxColumn colRewardAndPenalties = new DataGridViewTextBoxColumn();
            colRewardAndPenalties.HeaderText = "奖惩";
            colRewardAndPenalties.Width = 100;
            colRewardAndPenalties.Name = "RewardAndPenalties";
            colRewardAndPenalties.ReadOnly = false;
            colRewardAndPenalties.Visible = true;
            colRewardAndPenalties.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colRewardAndPenalties.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //OverSpend, AddAndReduce, OverTimeSalary, Subsidy, WithHoldAndRemitTax
            DataGridViewTextBoxColumn colOverSpend = new DataGridViewTextBoxColumn();
            colOverSpend.HeaderText = "超耗";
            colOverSpend.Width = 100;
            colOverSpend.Name = "OverSpend";
            colOverSpend.ReadOnly = false;
            colOverSpend.Visible = true;
            colOverSpend.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colOverSpend.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colAddAndReduce = new DataGridViewTextBoxColumn();
            colAddAndReduce.HeaderText = "补或扣";
            colAddAndReduce.Width = 100;
            colAddAndReduce.Name = "AddAndReduce";
            colAddAndReduce.ReadOnly = false;
            colAddAndReduce.Visible = true;
            colAddAndReduce.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colAddAndReduce.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colOverTimeSalary = new DataGridViewTextBoxColumn();
            colOverTimeSalary.HeaderText = "加班工资";
            colOverTimeSalary.Width = 100;
            colOverTimeSalary.Name = "OverTimeSalary";
            colOverTimeSalary.ReadOnly = false;
            colOverTimeSalary.Visible = true;
            colOverTimeSalary.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colOverTimeSalary.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colSubsidy = new DataGridViewTextBoxColumn();
            colSubsidy.HeaderText = "补助";
            colSubsidy.Width = 100;
            colSubsidy.Name = "Subsidy";
            colSubsidy.ReadOnly = false;
            colSubsidy.Visible = true;
            colSubsidy.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSubsidy.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWithHoldAndRemitTax = new DataGridViewTextBoxColumn();
            colWithHoldAndRemitTax.HeaderText = "代或缴";
            colWithHoldAndRemitTax.Width = 100;
            colWithHoldAndRemitTax.Name = "WithHoldAndRemitTax";
            colWithHoldAndRemitTax.ReadOnly = false;
            colWithHoldAndRemitTax.Visible = true;
            colWithHoldAndRemitTax.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWithHoldAndRemitTax.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            // Remark, Posted,RecID, ValueChanged, DelButton
            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Width = 100;
            colRemark.Name = "Remark";
            colRemark.ReadOnly = false;
            colRemark.Visible = true;

            DataGridViewTextBoxColumn colPosted = new DataGridViewTextBoxColumn();
            colPosted.HeaderText = "post标志";
            colPosted.Width = 100;
            colPosted.Name = "posted";
            colPosted.ReadOnly = false;
            colPosted.Visible = false ;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RowSeqNo = 0, WorkDate, WorkShopSeqNo, WorkShopName, WorkerRecID, WorkerID, WorkerName, 
            //HourlySalary, HourlyCost, HoursOnCost, RewardAndPenalties, OverSpend, AddAndReduce, OverTimeSalary, Subsidy, 
            //WithHoldAndRemitTax, Remark, Posted,
            //RecID, ValueChanged, DelButton 
            this.dgvInputDtl.Columns.AddRange(new DataGridViewColumn[] {  
                colRowSeqNo,colSel,colWorkDate,colWorkShopSeqNo,colWorkShopName, colWorkerRecID, colWorkerID,colWorkerName,
                colHourlySalary,colHourlyCost,colHoursOnCost,colPRPSalary,colRewardAndPenalties,colOverSpend,colAddAndReduce,colOverTimeSalary,colSubsidy,
                colWithHoldAndRemitTax,colRemark,colPosted,
                colRecID, colValueChanged, colDel  });

            mDtlColumnReadOnlyArray = new bool[dgvInputDtl.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvInputDtl.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvInputDtl.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvInputDtl.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvInputDtl.Columns.Count) dgvInputDtl.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvInputDtl.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvInputDtl.RowTemplate.Height = 20;
            this.dgvInputDtl.RowHeadersWidth = 23;
            this.dgvInputDtl.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvInputDtl.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvInputDtl.ColumnHeadersHeight = 30;
            this.dgvInputDtl.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvInputDtl.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvInputDtl.AllowUserToResizeRows = false;
        }

        private void FillDtl(string strCondSQL)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvInputDtl.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select * from "+ mstrTableName +" where posted = 0  {0}" ;
            strSql = string.Format(strSql, strCondSQL);
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];

            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvInputDtl.Rows.Count <= i) this.dgvInputDtl.Rows.Add();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvInputDtl.Rows.Count.ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.AddAndReduce].Value = BaseFunctions.FormatNumeric(dr["AddAndReduce"], "ns.2");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.HourlyCost].Value = BaseFunctions.FormatNumeric(dr["HourlyCost"], "ns.2");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Posted].Value =  CvtFunc.ToBoolean(dr["Posted"])  ;
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = dr["RecID"].ToString().TrimEnd();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Remark].Value = dr["Remark"].ToString().TrimEnd();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.HourlySalary].Value = dr["HourlySalary"].ToString().TrimEnd();

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.HoursOnCost].Value = BaseFunctions.FormatNumeric(dr["HoursOnCost"], "Ns.2");

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.PRPSalary].Value = BaseFunctions.FormatNumeric(dr["PRPSalary"], "Ns.2");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.OverSpend].Value = dr["OverSpend"].ToString().TrimEnd();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.OverTimeSalary].Value = dr["OverTimeSalary"].ToString();

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RewardAndPenalties].Value = dr["RewardAndPenalties"].ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Subsidy].Value = dr["Subsidy"].ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WithHoldAndRemitTax].Value = dr["WithHoldAndRemitTax"].ToString();

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkDate].Value = BaseFunctions.FormatDate( CvtFunc.ToString (dr["WorkDate"]), DateFormatOption.DateFmtMDY);
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkerID].Value = CvtFunc.ToString ( dr["WorkerID"]) ;
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkerName].Value = dbCon.GetValue ("select WorkerName from rmWorker where WorkerID='"+ dr["WorkerID"] +"'");
                               
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkShopSeqNo].Value = dr["WorkShopSeqNo"].ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkShopName].Value = dbCon.GetValue("select workshopname from rmWorkShop where WorkShopSeqNo='"+ dr["WorkShopSeqNo"] +"'");

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Remark].Value = dr["Remark"];                 
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
            }//
            base.SetBlankImage(dgvInputDtl);
            if (dgvInputDtl.Rows.Count == 0)
            {
                AddDtlRow(this.dgvInputDtl.Name);
            }
            dbCon.CloseCon();          
        
            m_bCanTrigerCellValueChangedEven = true;
        }
        private void dgvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvInputDtl.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvInputDtl.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex);
                }
            }
            else
            {
                if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && base.HasDelImage(this.dgvInputDtl, e))
                {
                    this.dgvInputDtl.CurrentCell.Selected = true;
                    this.dgvInputDtl.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvInputDtl.Rows.Remove(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]);
                    if (this.dgvInputDtl.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvInputDtl.Name);
                    }
                }
            }
        }
         
        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvInputDtl.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvInputDtl.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvInputDtl.Rows.Add();
                    intRow = this.dgvInputDtl.Rows.Count - 1;
                }                
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvInputDtl.Rows.Count.ToString();
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.AddAndReduce].Value = BaseFunctions.FormatNumeric("0", "ns.2");
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.HourlyCost].Value = BaseFunctions.FormatNumeric("0", "ns.2");
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.HourlySalary].Value = BaseFunctions.FormatNumeric("0", "ns.0");
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.OverSpend].Value = "0.00";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.OverTimeSalary].Value = "0.00";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.RewardAndPenalties].Value = "0.00";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Subsidy].Value = "0.00";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WithHoldAndRemitTax].Value = "0.00";
                
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Posted].Value = "0";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.RecID].Value = "-1";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Remark].Value = "";
                

                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkDate].Value = BaseFunctions.FormatDate( DateTime.Now.Date.ToShortDateString() , DateFormatOption.DateFmtMDY);
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerID].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerName].Value = "";

                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkShopSeqNo].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkShopName].Value = "";

                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Remark].Value = "";                
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvInputDtl.CurrentCell = dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkShopSeqNo];
                m_bCanTrigerCellValueChangedEven = true;
            }
        }
        private void Dtl_LookUp(int iColumnIndex)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            switch ((DtlCol)iColumnIndex)
            {
                case DtlCol.WorkShopSeqNo:
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkShop");
                    strCaption = "车间选择";
                    if (this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value != null) strFindValue = this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value.ToString();
                    strFindField = "WorkShopSeqNo";
                    break;
                case DtlCol.WorkerID:
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorker");
                    strCaption = "员工工号";
                    if (this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value != null) strFindValue = this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value.ToString();
                    strFindField = "WorkerID";
                    break;
               
            }

            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            frmLookUp frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
            frmlookup.ShowDialog();

            if (frmlookup.HaveReturnValue)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WorkShopSeqNo:
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopSeqNo].Value = frmlookup.GetReturnValue("WorkShopSeqNo");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopName].Value = frmlookup.GetReturnValue("WorkShopName");
                        break;
                    case DtlCol.WorkerID:
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = frmlookup.GetReturnValue("WorkerID");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = frmlookup.GetReturnValue("RecID");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = frmlookup.GetReturnValue("WorkerName");
                        break;
                 
                }
                GetWorkerInfoByWorkerID( CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value));
            }
            frmlookup.Close();
        }

        private void GetWorkerInfoByWorkerID(string strWorkerID)
        {
            string strSQL = "select * from rmWorker where WorkerID='" + strWorkerID + "'";
            DBAccess dbcon = new DBAccess(false, false);
            DataRow drWorkInfo = dbcon.GetDataFirstRow(strSQL);
            if (drWorkInfo != null)
            {
                if (CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopSeqNo].Value) == "")
                {
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopSeqNo].Value = CvtFunc.ToString(drWorkInfo["WorkShopSeqNo"]);
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopName].Value = dbcon.GetValue ("select workshopname from rmWorkShop where WorkShopSeqNo='"+ drWorkInfo["WorkShopSeqNo"] +"'");
                }              
               
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = CvtFunc.ToString(drWorkInfo["RecID"]);
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = CvtFunc.ToString(drWorkInfo["WorkerID"]);
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = CvtFunc.ToString(drWorkInfo["WorkerName"]);                
            }
            dbcon.CloseCon(); 
        }

        private double CalWorkSalary(double dblHourlyCost, double dblHourlyOnCost)
        {
            return dblHourlyCost * dblHourlyOnCost; 
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvInputDtl.ColumnCount - 1; i++)
            {

                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            if (CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value).Length ==0)
            {
                strErrMsg = "员工姓名不能为空";
                bCheckResult = false;
            }            
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "",strValue_WorkerID="";
            if (this.dgvInputDtl.CurrentRow != null && this.dgvInputDtl.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[iColumn].Value);
                strValue_WorkerID = CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value);
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WorkerName:
                    if (strValue.Trim() == "" && CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value) !="")
                    {
                        strErrMsg = "员工姓名不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorker", strValue_WorkerID, "WorkerID") && CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value) != "")
                    {
                        strErrMsg = "不存在的员工姓名";
                        return false;
                    }
                    return true;              
                case DtlCol.WorkShopSeqNo:
                    if (strValue =="")
                    {
                        strErrMsg ="车间不能为空。";
                    }
                    break;
                case DtlCol.WorkDate :
                    if (!BaseFunctions.IsDate(strValue))
                    {
                        strErrMsg = "必须是正确的日期。";
                        return false;
                    }
                    else
                    {
                        if (!DataFunctions.CheckDateInCurPeriod(strValue))
                        {
                            strErrMsg = "日期不在当前会计区间，不能添加。";
                            return false;
                        }
                    }
                    break;
            }
            return bReturnValue;
        }
        private void dgvDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvInputDtl.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvInputDtl") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (mPressExit) { e.Cancel = false; return; };
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void dgvDetail_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvInputDtl.CurrentRow != null && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvInputDtl") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (mPressExit) { e.Cancel = false; return; };
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        private void dgvDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvInputDtl.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            
            dgvInputDtl.EndEdit();
            DBAccess dbcon = new DBAccess(false, false);
            {
                if (e.ColumnIndex == (int)DtlCol.WorkerID)
                {
                    string strNamePY = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value);
                    string strSQL = "select * from rmWorker where WorkerID ='" + strNamePY + "'";
                    DataTable dtWorker = dbcon.GetDataTable(strSQL);
                    foreach (DataRow drWorker in dtWorker.Rows)
                    {
                        if (dtWorker.Rows.Count == 1)
                        {
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = drWorker["WorkerID"];
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = drWorker["RecID"];
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = drWorker["WorkerName"];
                        }
                    }
                }
                else if (e.ColumnIndex == (int)DtlCol.WorkShopSeqNo)
                {
                    string strWorkPositionSeqNo = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkShopSeqNo].Value);    
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = dbcon.GetValue (string.Format ( @"select WorkShopName from rmworkshop Where WorkShopSeqNo='{0}'", strWorkPositionSeqNo)) ;
                }
                else if (e.ColumnIndex == (int)DtlCol.HourlyCost
                              || e.ColumnIndex == (int)DtlCol.HoursOnCost)
                {
                    double dblWorkSalary = CalWorkSalary(CvtFunc.ToDouble(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.HourlyCost].Value)
                                                        , CvtFunc.ToDouble(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.HoursOnCost].Value)
                                                       );
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.HourlySalary].Value = BaseFunctions.FormatNumeric(dblWorkSalary, "Ns.2");
                }
            }
            dbcon.CloseCon(); 
            dgvInputDtl.EndEdit();
        }
        private void dgvDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvInputDtl.CurrentCell.Selected = false;
            }
            SetColReadOnly();
        }

        private void SetColReadOnly()
        {
            if (CvtFunc.ToBoolean(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.Posted].Value))
            {
                this.dgvInputDtl.CurrentCell.ReadOnly = true;
            }
            else
            {
                if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.RowSeqNo
                    || this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.WorkerName
                    || this.dgvInputDtl.CurrentCell.ColumnIndex ==(int)DtlCol.WorkShopName  
                 )
                {
                    this.dgvInputDtl.CurrentCell.ReadOnly = true;
                }
                else
                {
                    this.dgvInputDtl.CurrentCell.ReadOnly = false;
                }
            }
        }

        private void dgvDetail_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvInputDtl.CurrentCell.Selected = false;
            }
        }
        private void dgvDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }
        private void dgvDetail_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvInputDtl, e, (int)DtlCol.DelButton);
            string strErrMsg = "";
            if (dgvInputDtl.CurrentRow != null && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                    {
                        return;
                    }

                    //AddDtlRow(this.dgvInputDtl.Name);
                }
                else
                {
                    return;
                }
            }
            
        }
        private void dgvDetail_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvInputDtl.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvInputDtl.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvInputDtl.Name))
            {
                blnRet = dgvDetail_KeyDownEvent(keyData);
            }          

            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }
        private bool dgvDetail_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvInputDtl.EndEdit();
                    if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvInputDtl.CurrentCell.RowIndex < dgvInputDtl.Rows.Count - 1)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WorkerID];
                        }
                        else
                        {
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvInputDtl.CurrentCell.RowIndex > 0)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.RowSeqNo];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            if (dgvInputDtl.CurrentCell.RowIndex > 0)
                            {
                                dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.RowSeqNo];
                            }
                        }
                        else if (dgvInputDtl.Rows.Count > 1)
                        {

                            this.dgvInputDtl.Rows.Remove(this.dgvInputDtl.CurrentRow);
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvInputDtl.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvInputDtl);
                    if (dgvInputDtl.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvInputDtl.CurrentCell.RowIndex < dgvInputDtl.Rows.Count - 1)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WorkerID];
                        }
                        else
                        {
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvInputDtl, dgvInputDtl.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            this.dgvInputDtl.EndEdit();
            DBAccess dbcon = new DBAccess(false, false);
            string strFields = "WorkDate,PrdYear,PrdMonth,WorkShopSeqNo,WorkerID,WorkPositionSeqNo,HourlySalary,HourlyCost,HoursOnCost,PRPSalary,RewardAndPenalties,OverSpend,AddAndReduce,OverTimeSalary,Subsidy,WithHoldAndRemitTax,Remark,Posted";
            try
            {
                DataRow drDtl = dbcon.GetDataTable("select * from " + mstrTableName + " ").NewRow();
                strSQL = "SELECT Period,StPrdDate FROM MPERIOD where StPrdDate<='{0}' and EnPrdDate>='{0}'";
                strSQL = string.Format(strSQL, dgvRow.Cells[(int)DtlCol.WorkDate].Value);
                DataRow drPrd = dbcon.GetDataFirstRow(strSQL);

                if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)   //Update
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);                   
                    if (drDtl != null)
                    {
                        drDtl["PrdYear"] =  CvtFunc.ToDateTime( drPrd["StPrdDate"]).Year.ToString ()    ;
                        drDtl["PrdMonth"] = CvtFunc.ToString(drPrd["Period"]); 
                    }
                    DataFunctions.UpdateTable(dbcon, strFields, mstrTableName, drDtl, FormStatus.Update);
                }
                else //Add New
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);
                    if (drDtl != null)
                    {
                        drDtl["PrdYear"] = CvtFunc.ToDateTime(drPrd["StPrdDate"]).Year.ToString();
                        drDtl["PrdMonth"] = CvtFunc.ToString(drPrd["Period"]);
                    }
                    DataFunctions.UpdateTable(dbcon, strFields, mstrTableName, drDtl, FormStatus.AddNew);
                    dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drDtl["RecID"]);
                }
                dbcon.CloseCon();
            }
            catch (Exception ex)
            {
                dbcon.CloseCon();
                return false;
            }
            return true;
        }
        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return true;
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RecID].Value);
            string strSeqNo = CvtFunc.ToString(dgvRow.Cells["RowSeqNo"].Value);
            string strSQL = string.Empty;
            if (CvtFunc.ToDouble(strRecID) > 0)
            {
                if (MessageBox.Show("您确定要删除？", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DBAccess dbcon = new DBAccess(false, false);
                    try
                    {
                        dbcon.BeginTran();
                        strSQL = "Delete " + mstrTableName + " where RecID='" + strRecID + "'";
                        dbcon.ExecuteSql(strSQL);
                        dbcon.CommitTran(); 
                    
                        //string strWKProductID = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WKProductID].Value);
                        //string strWKPriceType = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WKPriceType].Value);
                        //strSQL = "select * from imCategoryWKWorkCost where WKProductID='" + strWKProductID + "' and WKPriceType='" + strWKPriceType + "'";
                        //DataTable dtFind = dbcon.GetDataTable(strSQL);
                        //if (dtFind.Rows.Count > 0)
                        //{
                        //    if (MessageBox.Show("其他类别有相同的费用标准，是否也删除？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        //    {
                        //        foreach (DataRow drRow in dtFind.Rows)
                        //        {
                        //            strSQL = "Delete " + mstrTableName + " where RecID='" + drRow["RecID"] + "'";
                        //            dbcon.ExecuteSql(strSQL);
                        //        }
                        //    }
                        //}
                    }
                    catch (Exception ex)
                    {
                        dbcon.RollbackTran();
                    }
                    dbcon.CloseCon();
                }
            }
            return true;
        }
        private void dgvDetail_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvInputDtl.EndEdit();

            if (e.ColumnIndex == (int)DtlCol.WorkerID)
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvInputDtl.Rows[e.RowIndex]);
                }
            }
        }

        #endregion

        private void dgvInputDtl_Enter(object sender, EventArgs e)
        {
            if (!UpdateData())
            {
                //txtWorkQty.Focus();
            }
            else
            {
                //txtWorkingProcedureID.ReadOnly = true ; 
            }
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            string strAddCondition = "";
            frmRMSalaryAddMulitLinesByCond frmAdd = new frmRMSalaryAddMulitLinesByCond();
            strAddCondition = frmAdd.GetAddCond();
            if ( strAddCondition != "")
            {
                int intRow = this.dgvInputDtl.Rows.Count ;
                string strErrMsg = "";
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return ;
                    AddLineByCondition(intRow, strAddCondition); 
                }
            }
        }

        private void AddLineByCondition( int intRow , string strCondition)
        {
            string strSQL = "";
            
            strSQL = "select * from rmWorker where 1=1 And " + strCondition;
            using ( DBAccess dbcon =new DBAccess ( false,false ))
            {
                DataTable dtWorker = dbcon.GetDataTable(strSQL);
                foreach (DataRow drWorker in dtWorker.Rows)
                {
                    AddDtlRow(this.dgvInputDtl.Name);
                    this.dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[this.dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo];    
                    GetWorkerInfoByWorkerID( CvtFunc.ToString(drWorker["WorkerID"]));
                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return;
                }
            }
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            this.dgvInputDtl.EndEdit();

            using (DBAccess dbcon = new DBAccess(false, false))
            {
                
                foreach (DataGridViewRow dgvRow in this.dgvInputDtl.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["Sel"].Value))
                    {
                        Posted(dbcon, CvtFunc.ToString ( dgvRow.Cells["RecID"].Value));
                    }
                }
            }
            FillDtl(""); 
        }

        private bool Posted(DBAccess dbcon , string strRecID)
        {
            string strSQL = "update "+ mstrTableName +" Set Posted=1 Where RecID='"+ strRecID +"'";
            dbcon.ExecuteSql(strSQL); 
            return true;
        }

        private void btnSelAll_Click(object sender, EventArgs e)
        {
            SelAndUnSel(true);
        }

        private void btnUnSelAll_Click(object sender, EventArgs e)
        {
            SelAndUnSel(false);
        }

        private void SelAndUnSel(bool blnSel)
        {
            foreach (DataGridViewRow dgvRow in this.dgvInputDtl.Rows)
            {
                //if (!CvtFunc.ToBoolean(dgvRow.Cells[(int)DtlCoumn.Posted].Value))
                {
                    dgvRow.Cells[(int)DtlCol.Sel].Value = blnSel;
                }
            }
            this.dgvInputDtl.EndEdit();
        }
    }
}
